package com.credit.core.config;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.credit.core.config.Config;
import com.credit.core.config.ZooKeeperConfig;
 

/**    
 *     
 * 项目名称：core    
 * 类名称：ZooKeeperPropertyPlaceholderConfigurer    
 * 类描述：    zookeeper 配置中心处理类
 * 创建人：huan    
 * 创建时间：2016年3月21日 下午2:57:11    
 * 修改人：huan    
 * 修改时间：2016年3月21日 下午2:57:11    
 * 修改备注：    
 * @version     
 *     
 */
public class ZooKeeperPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
     
    public static final String PATHS = "zoo.paths";
    
    private Properties properties;
 
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException {
        try {
            fillCustomProperties(props);
        }
        catch (Exception e) {
            // Ignore
            e.printStackTrace();
        }
        super.processProperties(beanFactoryToProcess, props);
    }
 
    private void fillCustomProperties(Properties props) throws Exception {
    	String paths =  props.getProperty(PATHS);
    	for(String path :paths.split(",")){
    		byte[] data = getData(props , path);
    		fillProperties(props, data);
    	}
    }
 
    private void fillProperties(Properties props, byte[] data) throws UnsupportedEncodingException {
        String cfg = new String(data, "UTF-8");
        if (StringUtils.isNotBlank(cfg)) {
             // 完整的应该还需要处理：忽略#号开头（暂未处理）
        	String[] config = cfg.split("\n");
        	for(String configRecord :config ){
        		String[] cfgItem = StringUtils.split(configRecord, "=");
        		props.put(cfgItem[0], cfgItem[1]);
        	}
        }
        setProperties(props);
    }
 
    private byte[] getData(Properties props , String path) throws Exception {
        Config config = new ZooKeeperConfig();
        return config.getConfig(path);
    }
    
    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @SuppressWarnings("unused")
    private Properties getContextProperty(){
        return getProperties();
    }
 
}
